# -*- coding: utf-8 -*-

"""
Module implementing MainWindow.
"""
import sys, pymysql,datetime

import pandas as pd
#进程函数
import threading
import baostock as bs
from queue import Queue
from PyQt5.QtGui import QStandardItem, QBrush, QColor
from PyQt5.QtCore import pyqtSlot, Qt, QUrl
from PyQt5.QtWidgets import QMainWindow, QApplication, QTableWidgetItem, QHeaderView
from PyQt5.QtWebEngineWidgets import QWebEngineView

from Ui_mian import Ui_MainWindow
from PyQt5.QtGui import QMovie
#自定义函数
from dbManagement import DataManagement
from Multi_threading import Multi_threading


class MainWindow(QMainWindow, Ui_MainWindow):
    """

    现在需要测试多进程函数。如果成功能大大提升速度并解决个股跟踪问题
    存在的问题：
    1、同步个股走势需要添加；
    2、格式布局还有问题。
    3、计算平均走势；
    4、盘中跟踪放量等要放到多进程内；
    5、很多函数的初始化要放到多进程内处理。提高速度
    """

    def __init__(self, parent=None):
        #初始化函数
        self.ri_qi_arry = []
        self.ri_qi_arry2 = []
        self.stock_list = []
        self.dian_ji_shu_ju = []
        self.liu_tong_shi_zhi = []
        #初始化几个函数
        self.conn = DataManagement()
        self.M_threading = Multi_threading()

        # 连接数据库
        self.cursor = self.conn.connect_sql()
        # 获取stocklist总行数
        self.stocklist_zong_hang_shu = self.conn.stocklist_zong_hang_shu()

        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        #获取日期数组，调试正确
        (self.ri_qi_arry,self.ri_qi_arry2)= self.M_threading.jian_li_shu_zu()
        #开始增加线程，初始后台函数

        q = Queue()
        #获取板块示例
        #thread_ddd = threading.Thread(target=self.M_threading.job_get_data_get_net, args=("801122",self.liu_tong_shi_zhi,q))
        #thread_ddd.start()



        #for _ in range(10):
        #    self.liu_tong_shi_zhi.append(q.get()) # 从q中拿出值，每次只能按顺序拿出一个值
        #print(self.liu_tong_shi_zhi)

        self.zheng_li_list()
        self.xie_ru_shu_ju()
        self.xia_biao_shu_ju(self.stock_list)
        #self.hang_qing_shu_ju(self.stock_list)



        # 连接信号槽#########单击




        self.tableWidget_1.cellClicked['int', 'int'].connect(self.on_tabWidget_tabBarClicked)
        #要靠多线程来执行
        self.tableWidget_2.cellClicked['int', 'int'].connect(self.on_tabWidget_tabBarClicked_2)




    # 整理数据库股票列表去重
    def zheng_li_list(self):
        aa = []
        cc = self.conn.stocklist_zong_hang_shu()
        for i in range(cc):
            rowCount = self.cursor.fetchone()
            # print(rowCount)
            # self.newstocklist rowCount[1]
            rowCount = rowCount[1]
            aa.append(rowCount)
            self.stock_list = list(set(aa))
            self.stock_list.sort(key=aa.index)

    # 写入数据建立板块表格
    def xie_ru_shu_ju(self):
        for f in range(len(self.ri_qi_arry2)):
            item1 = QTableWidgetItem(self.ri_qi_arry2[f])
            item2 = QTableWidgetItem(self.ri_qi_arry[f])
            item3 = QTableWidgetItem('综合评价')
            item4 = QTableWidgetItem('盘整力度')
            ################################ 修改行标头
            self.tableWidget_2.setHorizontalHeaderItem(0, item3)
            self.tableWidget_2.setHorizontalHeaderItem(1, item4)
            self.tableWidget_2.setHorizontalHeaderItem( f + 2, item1)
            self.tableWidget_1.setHorizontalHeaderItem(f, item2)
            ############################### 如果是交易日，那么就要循环，写入前五大板块信息
            cc = self.conn.zhi_ding_jiao_yi_ri_shu_ju(self.ri_qi_arry[f])
            for it in range(cc):
                it1 = self.cursor.fetchone()
                if it >= 5:
                    break
                else:
                    ######################### 获取指定数列段
                    it2 = it1[2]
                    it3 = it1[4]
                    it4 = it3 + "(" + ('%s') % it2 + ")"
                    ######################### 写入每日前五大板块及板块涨停个数
                    it5 = QTableWidgetItem(it4)
                    it5.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                    self.tableWidget_1.setItem(it, f, it5)
                    self.tableWidget_1.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
                    self.tableWidget_1.setColumnWidth(0, 20)
                    self.tableWidget_1.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)


        # country_item1 = QTableWidgetItem('还是我')
        # country_item2 = QTableWidgetItem('我')
        # country_item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        # 现在创建一个关于国家的表格对象。这个国家的单元格对象里面放入国旗和国家名称，单元格的对齐方式是：水平、垂直居中。
        # 下同
        # 修改列表头
        # self.tableWidget.setVerticalHeaderItem(0,country_item1)
        # 修改行标头
        # self.tableWidget.setHorizontalHeaderItem(0, country_item2)
        # 修改单元格内容
        # self.tableWidget.setItem(0, 0, country_item)

    ######################################## 写入数据建立下表表格
    def xia_biao_shu_ju(self,stock_list):

        for f in range(len(stock_list)):
            item = QTableWidgetItem(stock_list[f])
            # 修改行标头
            self.tableWidget_2.setVerticalHeaderItem(f, item)

    #获取行情数据并写入中表单元格内
    def hang_qing_shu_ju(self,stock_list):
        #### 登陆系统 ####
        lg = bs.login()
        a = self.conn.pan_duan_jiao_yi_ri()

        for f in range(len(stock_list)):
            aaa = 'sz.%s' % stock_list[f]
            bbb = 'sh.%s' % stock_list[f]
            # 数组内的格式是倒的
            if stock_list[f][0:2] != "60":
                rs = bs.query_history_k_data_plus(aaa,
                                                  "pctChg",
                                                  start_date=self.ri_qi_arry[19], end_date=self.ri_qi_arry[0],
                                                  frequency="d", adjustflag="3")

            else:
                rs = bs.query_history_k_data_plus(bbb,
                                                  "pctChg",
                                                  start_date=self.ri_qi_arry[19], end_date=self.ri_qi_arry[0],
                                                  frequency="d", adjustflag="3")
            data_list = []
            bo_dong = []
            while (rs.error_code == '0') & rs.next():
                # 获取一条记录，将记录合并在一起

                data_list.append(rs.get_row_data())

                self.result = pd.DataFrame(data_list, columns=rs.fields)

            # print(data_list)

            # 把数组颠倒过来
            list_2 = [data_list[0]]

            for i in range(1, len(data_list)):
                list_2.insert(0, data_list[i])
            # 开始放入单元格
            #判断交易时间
            if self.ri_qi_arry[0] == datetime.datetime.now().strftime("%Y-%m-%d") and a == 1:
                #print(datetime.datetime.now().strftime("%H:%M"))
                p = 3
                #启动一个线程，后台计算数值并写入单元格
                thread_huo_qu_ge_gu_hang_qing = threading.Thread(target=self.conn.huo_qu_dang_ri_hang_qing,
                                                                 args=(self.stock_list[f], self.ri_qi_arry[0]))
                thread_huo_qu_ge_gu_hang_qing.start()

            else:
                p = 2


            for d in range(len(list_2)):

                dddd = "%.2f" % float(list_2[d][0])
                # print(dddd)
                cccc = float(dddd)
                #大于9.8涨停个股标色
                if cccc >= 9.8:
                    self.tableWidget_2.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
                    shu_ju = QTableWidgetItem(dddd)
                    shu_ju.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                    #self.tableWidget_2.item(f, d).setForeground(QBrush(QColor(255,0,0)))
                    self.tableWidget_2.setItem(f, d + p, shu_ju)
                    self.tableWidget_2.item(f, d + p).setBackground(QColor("yellow"))  # 或用常见的颜色QColor("red")
                #5-9.8个股标色
                elif cccc >= 5 and cccc < 9.8:
                    self.tableWidget_2.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
                    shu_ju = QTableWidgetItem(dddd)
                    shu_ju.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                    # self.tableWidget_2.item(f, d).setForeground(QBrush(QColor(255,0,0)))
                    self.tableWidget_2.setItem(f, d + p, shu_ju)
                    self.tableWidget_2.item(f, d + p).setBackground(QColor(238,130,238))
                #5-0标色
                elif cccc >= 0 and cccc < 5:
                    self.tableWidget_2.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
                    shu_ju = QTableWidgetItem(dddd)
                    shu_ju.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                    # self.tableWidget_2.item(f, d).setForeground(QBrush(QColor(255,0,0)))
                    self.tableWidget_2.setItem(f, d + p, shu_ju)
                    self.tableWidget_2.item(f, d + p).setBackground(QColor(255,192,203))
                #-5 0标色
                elif cccc >= -5 and cccc < 0:
                    self.tableWidget_2.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
                    shu_ju = QTableWidgetItem(dddd)
                    shu_ju.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                    # self.tableWidget_2.item(f, d).setForeground(QBrush(QColor(255,0,0)))
                    self.tableWidget_2.setItem(f, d + p, shu_ju)
                    self.tableWidget_2.item(f, d + p).setBackground(QColor(127,255,170))
                #深调标色
                else:
                    shu_ju = QTableWidgetItem(dddd)
                    shu_ju.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                    self.tableWidget_2.setItem(f, d  + p, shu_ju)
                    self.tableWidget_2.item(f, d + p).setBackground(QColor( 0,128,0))
                    # print("no")

        bs.logout()
    # 单击槽函数，选出指定板块个股
    pyqtSlot(int, int)
    def on_tabWidget_tabBarClicked(self, row, column):
        #print(row,column)
        item1 = self.tableWidget_1.item(row, column).text()
        item2 = item1.split("(")[0]
        item3 = self.tableWidget_1.horizontalHeaderItem(column).text()

        item4 =self.M_threading.job_get_data_1(item2,item3)
        cc = len(item4)
        #以上都是对的
        self.tableWidget_2.clearContents()
        self.tableWidget_2.setRowCount(cc)
        self.xia_biao_shu_ju(item4)
        self.hang_qing_shu_ju(item4)

    #单击下表出现单日、分时走势
    pyqtSlot(int, int)
    def on_tabWidget_tabBarClicked_2( self, row, column):
        item1 = self.tableWidget_2.verticalHeaderItem(row).text()
        (item2,item3) = self.M_threading.huo_qu_zou_shi(item1)
        self.view_1.page().load(QUrl(item2))
        self.view.page().load(QUrl(item3))




    """
        
        
    """

















